﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;
using SAPbobsCOM;
using System.Text.RegularExpressions;
using BoAddonBiz_FreightForwarder.UpLoad;
using System.Collections;

namespace BoAddonBiz_FreightForwarder
{
    public class B1Form_BusinessOperationSonList : SAPBoAddon.B1Form
    {
        public B1Form_BusinessOperationSonList()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_BusinessOperationSonList_frm_ItemEvent);
        }

        void B1Form_BusinessOperationSonList_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                if (pVal.ItemUID == "7" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    Hide();
                    BubbleEvent = false;
                }
            }
            else
            {
                //选中单击的行
                if (pVal.ItemUID == "Grid" && pVal.Row >= 0 && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    SAPbouiCOM.Grid oGrid = CurrentFormEx.Items.Item("Grid").Specific;
                    oGrid.Rows.SelectedRows.Add(pVal.Row);
                }
                //grid的双击事件
                if (pVal.ItemUID == "Grid" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_DOUBLE_CLICK)
                {
                    Utils.ShowSonForm(SBOApp, this.CurrentForm.UniqueID, pVal.Row, this.ShowForm);
                }
                if (pVal.ItemUID == "btn_add" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.AddSonForm(SBOApp, this.CurrentForm.UniqueID, this.ShowForm);
                }
                if (pVal.ItemUID == "btn_del" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.DeleteSonForm(SBOApp, this.CurrentForm.UniqueID);
                }
            }
        }

        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.OpenVisiable = false;//默认打开不显示
            FormSetting.FormType = B1FormTypes.ado_AVA_FF_BusinessOpreationSonList;
            FormSetting.FormFileName = "AVA_FF_BusinessOperationSonListForm.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            // string parms = String.Format("{0};{1};{2};{3}", this.CurrentForm.UniqueID, sonTable, sonType, BNOEntry);
            this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value = InitPar.FatherFormUID.Split(';')[0];
            string sonType = InitPar.FatherFormUID.Split(';')[2];
            this.CurrentForm.DataSources.UserDataSources.Item("SonType").Value = sonType;
            string sonTable = InitPar.FatherFormUID.Split(';')[1];
            this.CurrentForm.DataSources.UserDataSources.Item("SonTable").Value = sonTable;
            string BNOEntry = InitPar.FatherFormUID.Split(';')[3];
            this.CurrentForm.DataSources.UserDataSources.Item("BNOEntry").Value = BNOEntry;
            string UDS = InitPar.FatherFormUID.Split(';')[4];//B1Form_BusinessOperation.CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}", sonTable))).Split(':')[2];
            Form fatherForm = SBOApp.Forms.Item(InitPar.FatherFormUID.Split(';')[0]);
            fatherForm.DataSources.UserDataSources.Item(UDS).Value = this.CurrentForm.UniqueID;//回写FormUID

            string sql = null;
            switch (sonType)
            {
                case B1FormTypes.ado_AVA_FF_Pickup:
                case B1FormTypes.ado_AVA_SE_Pickup:
                case B1FormTypes.ado_AVA_LN_Pickup:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID  ,U_SerialNum as 流水号, U_ConsignorName as 提货委托方 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_Delivery:
                case B1FormTypes.ado_AVA_SE_Delivery:
                case B1FormTypes.ado_AVA_LN_Delivery:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID  ,U_SerialNum as 流水号, U_ConsignorName as 委托陆运公司 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_Insure:
                case B1FormTypes.ado_AVA_SE_Insure:
                case B1FormTypes.ado_AVA_LN_Insure:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号, U_InsuranceCoName as 保险公司 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_ApplyCustoms:
                case B1FormTypes.ado_AVA_SE_ApplyCustoms:
                case B1FormTypes.ado_AVA_LN_ApplyCustoms:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号, U_CustomsBrokerName as 报关行 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_CustomsClearance:
                case B1FormTypes.ado_AVA_SE_CustomsClearance:
                case B1FormTypes.ado_AVA_LN_CustomsClearance:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号, U_CustomsBrokerName as 清关行 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_Storage:
                case B1FormTypes.ado_AVA_SE_Storage:
                case B1FormTypes.ado_AVA_LN_Storage:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号, U_BaseSerial as 业务号 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_FF_ArrivePort:
                case B1FormTypes.ado_AVA_SE_ArrivePort:
                case B1FormTypes.ado_AVA_LN_ArrivePort:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号, U_DelegateCardName as 指定代理 from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
                case B1FormTypes.ado_AVA_SE_Packing:
                    sql = String.Format("select DocEntry , CAST('' as nvarchar(100)) as FormUID   ,U_SerialNum as 流水号,U_PackStatus as 装箱状态  from [{0}] where U_BaseEntry='{1}'", sonTable, BNOEntry);
                    break;
            }
            DataTable table = this.CurrentForm.DataSources.DataTables.Item("DT");// this.CurrentForm.DataSources.DataTables.Add("Table");
            table.ExecuteQuery(sql);
            Grid grid = this.CurrentForm.Items.Item("Grid").Specific as Grid;

            grid.SelectionMode = BoMatrixSelect.ms_Single;
            grid.DataTable = table;
#if DEBUG
            grid.Columns.Item(0).Visible = true;//约定第一列一定是DocEntry
            grid.Columns.Item(3).Visible = true;//约定第二列一定是FormUID
#else
            grid.Columns.Item(0).Visible = false;//约定第一列一定是DocEntry
            grid.Columns.Item(3).Visible = false;//约定第二列一定是FormUID
#endif
        }

        /// <summary>
        /// 隐藏所有关联的子窗体
        /// </summary>
        private void Hide()
        {
            this.CurrentForm.Visible = false;//隐藏当前窗体，由主窗体触发统一的保存
            //隐藏所有关联的子窗体
            Grid grid = this.CurrentForm.Items.Item("Grid").Specific as Grid;
            for (int i = 0; i < grid.DataTable.Rows.Count; i++)
            {
                string formUid = grid.DataTable.GetValue("FormUID", i).ToString().Trim();
                foreach (Form form in SBOApp.Forms)
                {
                    if (form.UniqueID == formUid)
                    {
                        form.Visible = false;
                        break;
                    }
                }
            }
        }
    }

    /// <summary>
    /// 业务操作的子窗体基类
    /// </summary>
    /// <author>Webb.Wen</author>
    /// <create>2011-10-25 22:36:12</create>
    public abstract class B1Form_BaseOperationSon : SAPBoAddon.B1Form
    {
        /*
         * 由于业务操作的子窗体行为几乎一致，只是表现不同，所以抽象出了该基类
         * 该基类有如下行为
         * 1.添加状态下，uid=1触发隐藏操作；更新状态下，uid=1触发UI本身的更新操作
         * 2.添加完成后，清空父窗体的UserDataSource，并关闭自己，释放资源
         * 3.窗体本身被强制关闭时，同上
         * 4.窗体在InitializeForm时自动根据业务操作父窗体加载相关数据，包括同步客户等
         * 5.窗体打开默认不显示
         * 6.子窗体根据需要实现自己的ChooseFormListEvent
         */
        #region public properties
        /// <summary>
        /// [@AVA_FF_OBNO]表对应的是否***的字段
        /// </summary>
        public abstract string FatherField { get; }
        /// <summary>
        /// 业务操作父窗体的UserDataSource的ID
        /// </summary>
        public abstract string FatherUDS { get; }
        /// <summary>
        /// 当前对象的表名
        /// </summary>
        public abstract string ThisTableName { get; }
        /// <summary>
        /// 当前对象的子表名（如果有）
        /// </summary>
        public abstract string ThisSubTableName { get; }
        /// <summary>
        /// 当前对象的子表名（如果有）
        /// </summary>
        public abstract string ThisSubTableName2 { get; }
        /// <summary>
        /// 当前对象的名称
        /// </summary>
        public abstract string ThisObjectCode { get; }
        /// <summary>
        /// 通过父窗体取得父窗体的对象类型以及附件子表名称
        /// </summary>
        private string AVA_BNO5
        {
            get
            {
                Form listForm = SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value);
                Form BNOForm = SBOApp.Forms.Item(listForm.DataSources.UserDataSources.Item("ParentUID").Value);
                IEnumerator enumerator = BNOForm.DataSources.DBDataSources.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    DBDataSource dbds = enumerator.Current as DBDataSource;
                    if (dbds.TableName.ToUpper().EndsWith("BNO5"))
                    {
                        return dbds.TableName;
                    }
                }
                return "";
            }
        }

        protected Form BNOForm
        {
            get
            {
                string ParentUID = this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value;
                SAPbouiCOM.Form oListForm = SBOApp.Forms.Item(ParentUID);
                string FatherUID = oListForm.DataSources.UserDataSources.Item("ParentUID").Value;
                SAPbouiCOM.Form oParentForm = SBOApp.Forms.Item(FatherUID);
                return oParentForm;
            }
        }

        protected Form ListForm
        {
            get
            {
                string ParentUID = this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value;
                SAPbouiCOM.Form oListForm = SBOApp.Forms.Item(ParentUID);
                return oListForm;
            }
        }

        #endregion

        #region constructor
        public B1Form_BaseOperationSon()
        {            
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_BaseOperationSon_frm_ItemEvent);
            this.frm_AddonEvent += new frm_AddonEventEventHandler(B1Form_BaseOperationSon_frm_AddonEvent);
        }

        #endregion

        #region events

        void B1Form_BaseOperationSon_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    #region 注释
                    ////如果业务操作窗体是Add状态，触发隐藏操作，由主窗体的保存触发子窗体的保存
                    //if (BNOForm.Mode == BoFormMode.fm_ADD_MODE)
                    //{
                    //    this.CurrentForm.Visible = false;//隐藏当前窗体，由主窗体触发统一的保存
                    //    BubbleEvent = false;
                    //}
                    //else
                    //{
                    //    if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                    //    {
                    //        BubbleEvent = false;//在AfterAction里执行，让Button先回去焦点，不然最后一个焦点所在的控件的值还没有刷到DBDS里
                    //        this.CurrentForm.ActiveItem = "1";
                    //        Save();
                    //        this.CurrentForm.Mode = BoFormMode.fm_OK_MODE;
                    //        this.CurrentForm.Visible = false;
                    //    }
                    //    //如果当前窗体是更新状态，直接触发UI的更新，但是在触发以前要刷一下子表的DocEntry，不知道为什么子表的DocEntry为空
                    //    else if (this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
                    //    {
                    //        string docentry = this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).GetValue("DocEntry", 0);
                    //        if (!String.IsNullOrEmpty(ThisSubTableName))
                    //        {
                    //            for (int i = 0; i < this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).Size; i++)
                    //            {
                    //                this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).SetValue("DocEntry", 0, docentry.ToString());
                    //            }
                    //        }
                    //        if (!String.IsNullOrEmpty(ThisSubTableName2))
                    //        {
                    //            for (int i = 0; i < this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).Size; i++)
                    //            {
                    //                this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).SetValue("DocEntry", 0, docentry.ToString());
                    //            }
                    //        }
                    //        BubbleEvent = true;//更新的时候直接更新
                    //    }
                    //    else if (this.CurrentForm.Mode == BoFormMode.fm_FIND_MODE)
                    //    {
                    //        BubbleEvent = true;
                    //    }
                    //    else
                    //    {
                    //        this.CurrentForm.Visible = false;//隐藏当前窗体，由主窗体触发统一的保存
                    //        BubbleEvent = false;
                    //    }
                    //}
                    #endregion
                }
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)
                {
                    //在窗体是添加状态时，主动关闭时，视为放弃，从列表中删除
                    //其它状态下，也视为放弃，但是不影响数据库的操作,所以也没必要从列表中删除
                    if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                    {
                        Cancel();
                    }
                }
            }
            else
            {
                if (pVal.ItemUID == "btn_add" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    //隐藏当前窗体
                    this.CurrentForm.Visible = false;
                    //在ListForm里创建一个同级窗体并打开显示
                    Utils.AddSonForm(SBOApp, ListForm.UniqueID, this.ShowForm);
                }
                //上传附件 
                if (pVal.ItemUID == "Upload" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SAPbouiCOM.Form oParentForm = ActiveParentForm(CurrentForm);
                    int Currentrow = Utils.Add(SBOApp, oParentForm.UniqueID, AVA_BNO5);
                    BoAddonBiz_FreightForwarder.BusinessBase.B1Form_BusinessOperation_Base.FileCurrentOffset = Currentrow;
                    SAPbouiCOM.DBDataSource dbds = oParentForm.DataSources.DBDataSources.Item(AVA_BNO5);
                    dbds.SetValue("U_ToDocType", Currentrow, pVal.FormTypeEx);
                    Common_UpLoad upload = new Common_UpLoad();
                    upload.SetAffixInfo(oParentForm, AVA_BNO5, Currentrow);
                    //oParentForm.Select();
                    //oParentForm.PaneLevel = 6;
                }
                //下载附件 
                if (pVal.ItemUID == "Down" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    SAPbouiCOM.Form oParentForm = ActiveParentForm(CurrentForm);
                    string DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "l_base").ToString();
                    SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                    string SQL = @"select Max(U_FileName) FileName,Max(U_FilePath) ServerPath,Count(ISNULL(U_FilePath,'')) 
                            from [{2}] 
                            Where U_ToDocType = '{0}' And DocEntry = {1}
                            Group By U_FilePath Having Count(ISNULL(U_FilePath,'')) > 0";
                    ors.DoQuery(string.Format(SQL, CurrentForm.TypeEx, DocEntry, AVA_BNO5));
                    if (ors.RecordCount == 1)
                    {
                        string FileName = ors.Fields.Item("FileName").Value;
                        string ServerPath = ors.Fields.Item("ServerPath").Value;
                        Common_UpLoad Upload = new Common_UpLoad();
                        Upload.DownFile(FileName, ServerPath);
                    }
                    else
                    {
                        //如果有多条数据的话，显示一个列表，从列表中选择需要下载的行，再进行下载
                        ShowAllFile(CurrentForm.TypeEx, DocEntry);
                    }
                }
            }
        }
        void B1Form_BaseOperationSon_frm_AddonEvent(SAPBoAddon.B1AddonBase.AddonEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeEvent == false)
            {
                if (pVal.BaseEventType == SAPBoAddon.B1AddonBase.EnumBaseEventType.et_FormModeChanged)
                {
#if Relaese
                    if (CurrentForm.Mode == BoFormMode.fm_ADD_MODE || CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
                        (this.CurrentForm.Items.Item("1").Specific as Button).Caption = "保存";
                    if (CurrentForm.Mode == BoFormMode.fm_OK_MODE || CurrentForm.Mode == BoFormMode.fm_VIEW_MODE)
                        (this.CurrentForm.Items.Item("1").Specific as Button).Caption = "关闭";
#endif
                }
            }
        }
        #endregion

        #region override from B1Form
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
            //(this.CurrentForm.Items.Item("1").Specific as Button).Caption = "关闭";
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.OpenVisiable = true;//默认打开显示
            FormSetting.AutoGetObjectNextNumber = true;
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            this.CurrentForm.Freeze(true);           
            if (!String.IsNullOrEmpty(InitPar.FatherFormUID))
            {
                InitializeForm(InitPar.FatherFormUID);
                //检查附件是否存在
                CheckExistsAffix();

            }
            //(this.CurrentForm.Items.Item("1").Specific as Button).Caption = "关闭";
            this.CurrentForm.Items.Item("2").Visible = false;//只能设为不可见，不能删除，否则在需要关闭窗口的时候，Close()方法会弹出一个MessageBox来确认，影响删除动作
            this.CurrentForm.Freeze(false);
        }
        #endregion

        /// <summary>
        /// 激活父窗体
        /// </summary>
        /// <returns></returns>
        private Form ActiveParentForm(Form oForm)
        {
            string ParentUID = oForm.DataSources.UserDataSources.Item("ParentUID").Value;
            SAPbouiCOM.Form oListForm = SBOApp.Forms.Item(ParentUID);
            string FatherUID = oListForm.DataSources.UserDataSources.Item("ParentUID").Value;
            SAPbouiCOM.Form oParentForm = SBOApp.Forms.Item(FatherUID);
            return oParentForm;
        }

        /// <summary>
        /// 检查是否存在附件
        /// </summary>
        private void CheckExistsAffix()
        {
            string BaseEntry = string.Empty;
            SAPbouiCOM.Form oForm = CurrentForm;
            BaseEntry = SAPBoAddon.B1Assistant.Item.GetValue(oForm, "l_base").ToString();
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"select U_FilePath,Count(ISNULL(U_FilePath,'')) 
                            from [{2}] 
                            Where U_ToDocType = '{0}' And DocEntry = {1}
                            Group By U_FilePath Having Count(ISNULL(U_FilePath,'')) > 0";
            ors.DoQuery(string.Format(SQL, oForm.TypeEx, BaseEntry, AVA_BNO5));
            if (ors.RecordCount > 0)
                oForm.Items.Item("Down").Visible = true;
            else
                oForm.Items.Item("Down").Visible = false;

        }

        #region 多个附件下载
        /// <summary>
        /// 显示所有的附件
        /// </summary>
        /// <param name="FormType"></param>
        /// <param name="DocEntry"></param>
        private void ShowAllFile(string FormType, string DocEntry)
        {
            SAPBoAddon.B1FormList.B1FormListSetting oFormListSetting = new SAPBoAddon.B1FormList.B1FormListSetting("FileDown", SAPBoAddon.B1FormList.FL_FillValueType.AddonEdit);
            oFormListSetting.FormTitle = "可下载的附件";
            string SQL = @"SELECT U_FileName,U_FileNum,U_FileType,U_Pages,U_FilePath 
                                                                            FROM [{2}]
                                                                            Where U_ToDocType = '{0}' And DocEntry = {1}";
            oFormListSetting.ListSQL = string.Format(SQL, FormType, DocEntry, AVA_BNO5);

            oFormListSetting.FormType = CurrentForm.TypeEx;
            oFormListSetting.FormUID = CurrentForm.UniqueID;
            oFormListSetting.ItemUID = "Down";
            oFormListSetting.FillSelectedField = "Down";
            oFormListSetting.SelectionMode = BoMatrixSelect.ms_Single;

            oFormListSetting.FindField = "U_FileName";

            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Enabled = false;
            oFormListSetting.MtxColumns.Title = "文件名称";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Enabled = false;
            oFormListSetting.MtxColumns.Title = "文件编号";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Enabled = false;
            oFormListSetting.MtxColumns.Title = "文件类型";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Enabled = false;
            oFormListSetting.MtxColumns.Title = "页数";
            oFormListSetting.MtxColumns.Add();
            oFormListSetting.MtxColumns.Visible = false;
            oFormListSetting.MtxColumns.Title = "文件路径";

            SAPBoAddon.B1Addon.B1Addon.B1FormList.Form_CreateListForm(oFormListSetting);
            SAPBoAddon.B1Addon.B1Addon.B1FormList.B1ListFormEvent += new SAPBoAddon.B1FormList.B1FormList.B1ListFormEventEventHandler(B1FormList_B1ListFormEvent);

        }
        /// <summary>
        /// 列表窗体事件
        /// </summary>
        /// <param name="pVal"></param>
        /// <param name="BubbleEvent"></param>
        void B1FormList_B1ListFormEvent(SAPBoAddon.B1FormList.B1FormListEvents pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeEvent == false)
            {
                pVal.CloseForm = false;
                string FileName = pVal.SelectedDataTable.GetValue("U_FileName", 0);
                string ServerPath = pVal.SelectedDataTable.GetValue("U_FilePath", 0);
                Common_UpLoad oUpload = new Common_UpLoad();
                oUpload.DownFile(FileName, ServerPath);
            }
        }
        #endregion

        #region copy from
        /// <summary>
        /// 在添加状态下关闭窗口的时候，视为放弃，此时列表中对应的项也同时删除
        /// </summary>
        private void Cancel()
        {
            Grid grid = ListForm.Items.Item("Grid").Specific as Grid;
            for (int gridrow = 0; gridrow < grid.Rows.Count; gridrow++)
            {
                if (grid.DataTable.GetValue("DocEntry", gridrow).ToString().Trim() == this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).GetValue("DocEntry", 0).Trim())
                {
                    grid.DataTable.Rows.Remove(gridrow);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parms"></param>
        private void InitializeForm(string parms)
        {
            Form listForm = SBOApp.Forms.Item(parms.Split(';')[0]);
            Form BNOForm = SBOApp.Forms.Item(listForm.DataSources.UserDataSources.Item("ParentUID").Value);
            string BNOEntry = listForm.DataSources.UserDataSources.Item("BNOEntry").Value;
            this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value = parms.Split(';')[0];//指向父窗体
            string thisEntry = parms.Split(';')[2];//
            this.CurrentForm.DataSources.UserDataSources.Item("thisEntry").Value = thisEntry;
            Grid grid = listForm.Items.Item("Grid").Specific as Grid;

            /*如果有，查询，如果没有，添加并复制从*/
            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string query = String.Format("select DocEntry from [{0}] where U_BaseEntry = {1} and DocEntry = {2}", ThisTableName, BNOEntry, String.IsNullOrEmpty(thisEntry) ? "-1" : thisEntry);
            rs.DoQuery(query);
            if (rs.RecordCount > 0)//执行查询，并手动置为编辑模式
            {
                Find(thisEntry);
            }
            else//否则添加
            {
                CopyFrom();
            }
            Utils.UpdateListFormGrid(SBOApp, listForm.UniqueID, this.CurrentForm.UniqueID, this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).GetValue("DocEntry", 0).Trim());
        }
        /// <summary>
        /// 执行系统查询
        /// </summary>
        /// <param name="thisEntry"></param>
        private void Find(string thisEntry)
        {
            this.CurrentForm.Mode = BoFormMode.fm_FIND_MODE;//置为查找模式
            this.CurrentForm.Items.Item("3").Enabled = true;
            (this.CurrentForm.Items.Item("3").Specific as EditText).Value = thisEntry;
            this.CurrentForm.Items.Item("1").Click(BoCellClickType.ct_Collapsed);//执行系统查询，是因为如果有多个DBDS，给DBDS查询赋值会比较麻烦
        }
        /// <summary>
        /// 从业务单复制数据
        /// </summary>
        private void CopyFrom()
        {
            //this.CurrentFormEx.Menu.Item(B1MenuTypes.sys_Add).Activate();
            this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;//置为添加模式
            DBDataSource target = this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName);
            //框架是通过点*来触发的自动创建DocEntry动作，子单据不是通过这种方式打开，所以不会自动创建DocEntry，要手动赋值
            target.SetValue("DocEntry", 0, Utils.GetNextEntry(ThisObjectCode));

            DBDataSource source = null;
            IEnumerator dbdsEnumerator = BNOForm.DataSources.DBDataSources.GetEnumerator();
            while (dbdsEnumerator.MoveNext())
            {
                DBDataSource dbds = dbdsEnumerator.Current as DBDataSource;
                if (!new System.Text.RegularExpressions.Regex(@"\d+\b").Match(dbds.TableName).Success && dbds.TableName.ToUpper().EndsWith("OBNO"))
                    source = dbds;
            }

            Utils.CopyDBDS(source, target, null, null, null, true);//复制“客户”等信息

            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("U_BaseEntry", 0, source.GetValue("DocEntry", 0).Trim());
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("U_BaseSerial", 0, source.GetValue("U_SerialNum", 0).Trim());
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("U_Remarks", 0, "");
        }
        /// <summary>
        /// 复制从操作
        /// </summary>
        /// <param name="fatherFormUid"></param>
        private void CopyFrom(string fatherFormUid, string thisEntry)
        {
            this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;

            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("DocEntry", 0, thisEntry);
            Form fatherForm = SBOApp.Forms.Item(fatherFormUid);

            DBDataSource target = this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName);
            DBDataSource source = null;
            IEnumerator dbdsEnumerator = fatherForm.DataSources.DBDataSources.GetEnumerator();
            while (dbdsEnumerator.MoveNext())
            {
                DBDataSource dbds = dbdsEnumerator.Current as DBDataSource;
                if (!new System.Text.RegularExpressions.Regex(@"\d+\b").Match(dbds.TableName).Success && dbds.TableName.ToUpper().EndsWith("OBNO"))
                    source = dbds;
            }

            Utils.CopyDBDS(source, target, null, null, null, true);//复制“客户”等信息

            string fatherEntry = source.GetValue("DocEntry", 0).Trim();
            string fatherSarial = source.GetValue("U_SerialNum", 0).Trim();
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("DocEntry", 0, thisEntry);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("U_BaseEntry", 0, fatherEntry);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("U_BaseSerial", 0, fatherSarial);
        }
        /// <summary>
        /// 调用sql的保存，没有自动触发UI的保存，因为UI的保存会自动跳转到下一个单据的新增状态，而不会保留当前窗体
        /// </summary>
        /// <returns></returns>
        private void Save(bool log = true)
        {
            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            //更新最新的DocEntry
            string onnm = String.Format("select AutoKey,DfltSeries from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", this.ThisObjectCode);
            rs.DoQuery(onnm);
            string thisEntry = rs.Fields.Item("AutoKey").Value.ToString();
            string DfltSeries = rs.Fields.Item("DfltSeries").Value.ToString();

            string max = String.Format("select ISNULL( MAX(DocEntry),1) as MaxEntry from [{0}]", this.ThisTableName);
            rs.DoQuery(max);
            string maxEntry = rs.Fields.Item("MaxEntry").Value.ToString();
            if (Convert.ToInt32(maxEntry) >= Convert.ToInt32(thisEntry))
            {
                rs.DoQuery(String.Format("update ONNM set AutoKey = '{0}' where ObjectCode = '{1}'", Convert.ToInt32(maxEntry) + 1, this.ThisObjectCode));
                thisEntry = Convert.ToString(Convert.ToInt32(maxEntry) + 1);
            }

            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("DocEntry", 0, thisEntry);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("DocNum", 0, thisEntry);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("Object", 0, this.ThisObjectCode);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("Series", 0, DfltSeries);
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("UserSign", 0, this.SBOCompany.UserSignature.ToString());
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("CreateDate", 0, DateTime.Now.ToString("yyyyMMdd"));
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("CreateTime", 0, DateTime.Now.ToString("HHmm"));
            this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("DataSource", 0, "I");
            string sql = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName), 0);
            rs.DoQuery(sql);
            if (log)
            {
                this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName).SetValue("LogInst", 0, "1");
                string sql_log = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName), 0);
                sql_log = Regex.Replace(sql_log, ThisTableName, ThisTableName + "_LOG");
                rs.DoQuery(sql_log);
            }
            if (!String.IsNullOrEmpty(ThisSubTableName))
            {
                for (int i = 0; i < this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).Size; i++)
                {
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).SetValue("DocEntry", i, thisEntry);
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).SetValue("LineId", i, (i + 1).ToString());
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).SetValue("Object", i, this.ThisObjectCode);
                    sql = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName), i);
                    rs.DoQuery(sql);
                    if (log)
                    {
                        this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName).SetValue("LogInst", i, "1");
                        sql = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName), i);
                        sql = Regex.Replace(sql, ThisSubTableName, ThisSubTableName + "_LOG");
                        rs.DoQuery(sql);
                    }
                }
            }
            if (!String.IsNullOrEmpty(ThisSubTableName2))
            {
                for (int i = 0; i < this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).Size; i++)
                {
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).SetValue("DocEntry", i, thisEntry);
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).SetValue("LineId", i, (i + 1).ToString());
                    this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).SetValue("Object", i, this.ThisObjectCode);
                    sql = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2), i);
                    rs.DoQuery(sql);
                    if (log)
                    {
                        this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2).SetValue("LogInst", i, "1");
                        sql = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName2), i);
                        sql = Regex.Replace(sql, ThisSubTableName2, ThisSubTableName2 + "_LOG");
                        rs.DoQuery(sql);
                    }
                }
            }
            string update = String.Format("update ONNM set AutoKey = '{0}' where ObjectCode = '{1}'", Convert.ToInt32(thisEntry) + 1, this.ThisObjectCode);
            rs.DoQuery(update);
        }
        /// <summary>
        /// 添加一个新的同级子窗体
        /// </summary>
        private void AddNew()
        {
            Form ListForm = this.SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value);
            Grid grid = ListForm.Items.Item("Grid").Specific as Grid;

            string sonType = ListForm.DataSources.UserDataSources.Item("SonType").Value.Trim();
            string BNOEntry = ListForm.DataSources.UserDataSources.Item("BNOEntry").Value.Trim();
            string sonTable = ListForm.DataSources.UserDataSources.Item("SonTable").Value.Trim().Split('/')[0];
            Recordset rs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            //string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", sonType);
            //rs.DoQuery(onnm);
            //string thisEntry = rs.Fields.Item("AutoKey").Value.ToString();

            int maxEntry = 0;

            for (int i = 0; i < grid.DataTable.Rows.Count; i++)
            {
                maxEntry = grid.DataTable.GetValue("DocEntry", i) > maxEntry ? grid.DataTable.GetValue("DocEntry", i) : maxEntry;
            }
            string thisEntry = Convert.ToString(maxEntry + 1);

            //string update = String.Format("update ONNM set AutoKey = '{0}' where ObjectCode = '{1}'", Convert.ToInt32(thisEntry) + 1, sonType);
            //rs.DoQuery(update);//只要取，就直接更新递增流水，防止同步误差
            string parms = String.Format("{0};{1};{2}", ListForm.UniqueID, BNOEntry, thisEntry);
            if (grid.DataTable.Rows.Count > 0 && grid.DataTable.GetValue("DocEntry", 0).ToString() == "0")//默认有一个空行，DocEntry=0
            {
                grid.DataTable.Rows.Remove(0);
            }
            grid.DataTable.Rows.Add();
            grid.DataTable.SetValue("DocEntry", grid.DataTable.Rows.Count - 1, thisEntry);

            this.ShowForm(sonType, parms);
        }
        #endregion
    }
    /* Problems:
     * 给DBDS的DocEntry赋值后，会对原有U_**的值产生影响（丢失）
     * 所以只能在页面加载时给DocEntry赋一个初始流水值，而不能在Sql保存时临时更新一个新流水值
     * 基于这个原因必须要在每一次获取ONNM后都要手动更新一下，使得下一次获取是新流水
     * 
     */
}
